﻿namespace SsisLdapSource
{
    using global::SsisLdapSource.DirectoryServicesProtocolsExtensions;

    using Microsoft.SqlServer.Dts.Runtime.Wrapper;

    public partial class SsisLdapSource
    {
        // the following parameters are not relevant for Active Directory types, hence assigned 0
        private const int Precision = 0;
        private const int Scale = 0;
        private const int Codepage = 0;
        private const int StringBasedColumnMaxLen = 256;

        private void CreateOutputColumnsBasedOnActiveDirectorySchema()
        {

            var ldapMetaMapFactoryInitializationValues = new LdapMetaMapFactoryInitializationValues(
                GuidEncodedAttributeBinaryAttributes,
                SidEncodedAttributeBinaryAttributes,
                Int64EncodedAttributeDateTimeAttributes,
                StringEncodedIntAttributes,
                AttributesWhichMayRequireExpansion);

            var ldapMetaMapFactory = new LdapMetaMapFactory(ldapMetaMapFactoryInitializationValues);

            foreach (var attributeToLoad in AttributesToLoad)
            {
                CreateColumn(LdapConnection.GetAttributeMetaData(attributeToLoad, ldapMetaMapFactory));
            }
        }

        private void CreateColumn(LdapAttributeMetaMap map)
        {
            var ssisColumnType = DotNetToSSISTypeMapper.SSISTypeEquivalent(
                map.SemanticDotNetTypeEquivalent ?? map.RawDotNetTypeEquivalent);
            var outputColumn =
                ComponentMetaData.OutputCollection[0].OutputColumnCollection.New();

            outputColumn.Name = map.LdapDisplayName;
            outputColumn.SetDataTypeProperties(
                    ssisColumnType,
                    IsColumnStringBased(ssisColumnType) ? StringBasedColumnMaxLen : 0,
                    Precision,
                    Scale,
                    Codepage);
        }

        private static bool IsColumnStringBased(DataType ssisDataType)
        {
            return ssisDataType == DataType.DT_WSTR ||
                   ssisDataType == DataType.DT_STR ||
                   ssisDataType == DataType.DT_TEXT ||
                   ssisDataType == DataType.DT_NTEXT;
        }
    }
}
